import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index.vue'
import store  from '../store/index'

Vue.use(VueRouter)

// 路由表 
const routes = [
  { path: '/', name: 'home', component: Index }, //直接加载
  { 
    path: '/index', name: 'inedex', meta:{title:'欢迎光临XXX管理系统'}, component: () => import('../views/Index.vue'),
    //嵌套路由
    children:[
      { path: '/about', name: 'about',meta:{title:'关于我们'}, component: () => import('../views/AboutView.vue') }, //懒加载
      { path: '/system/users', name: 'users',meta:{title:'用户管理'}, component: () => import('../views/system/users/Index.vue') },
      { path: '/system/info', name: 'info',meta:{title:'用户信息'}, component: () => import('../views/system/info/Index.vue') },

      { path: '/goods', name: 'goods',meta:{title:'商品管理'}, component: () => import('../views/goods/Index.vue') },
    ]
  },
  { path: '/login', name: 'login', component: () => import('../views/Login.vue') },
 
 
]

// 创建一个路由对象
const router = new VueRouter({
  mode: 'history',  //路由模式 history|hash
  base: process.env.BASE_URL,  //base 路由
  routes //路由表
})


//路由导航守卫
router.beforeEach((to,from,next)=>{

  //设置标题 
  document.title=to.meta.title;

  // console.log('from: ', from);
  // console.log('to: ', to);

  //登录验证 
  if(store.state.user.Token.length>0  || to.path=='/login'){
    next(); //放行
  }else{
    if(sessionStorage.getItem('user')!=null){
      let user = JSON.parse(sessionStorage.getItem('user'))
      store.commit('setUser',user);
      next();
    }else{
      alert('你的登录状态已经丢失，请重新登录！');
      router.push('/login');
    }

   
  }
})



export default router
